(function (window) {
    var raxControl = {};
    
    function searchControllerScope(expr) {
        var mainContent = null;
        var ng = null;
        //往上找，找到所有窗口
        var _windowsData = [];
        var _curWindow = window;
        var i = 0;
        while (_curWindow) {
            _windowsData.push(_curWindow);
            //当前和父窗口相等，说明是同一个窗口了
            if (_curWindow === _curWindow.parent && _curWindow === _curWindow.top) {
                break;
            }
            _curWindow = _curWindow.parent;
        }
        _windowsData = _windowsData.reverse();
        // console.log(_windowsData);
        for (var i = 0; i < _windowsData.length; i++) {
            mainContent = _windowsData[i].jQuery(expr);
            ng = _windowsData[i].angular;
            // console.log(_windowsData[i].jQuery("body")[0]);
            // console.log(mainContent.size());
            if (mainContent.size() > 0) {
                break;
            } else {
                mainContent = null;
            }
        }
        if (!mainContent) {
            // alert("在当前窗口栈中，没有找到主窗口");
            console.warn("在当前窗口栈中，没有找到主窗口");
            return;
        }
        return ng.element(mainContent[0]).scope();
    };

    raxControl.searchControllerScope = searchControllerScope;

    var getUrlParam = function(url) {
        if(!url)return;
        var paramStr = url.split('?')[1];
        if(!paramStr) return;
        paramStr = paramStr.split('&');
        var res = {};
        for(var i=0; i<paramStr.length; i++){
            var p = paramStr[i].split('=');
            if(p.length===2){
                res[p[0]] = p[1];
            }
        }
        return res;
    };

    var urlHandler = function(url, serialParams, encode){
        if(!url) return;
        var paramStr = "";
        serialParams = $.extend(getUrlParam(url),serialParams);
        if(encode == null || encode){
            paramStr = $.param(serialParams);
        } else {
            // 此处只考虑参数是对象的形式
            for ( var k in serialParams) {
                var param = serialParams[k];
                var t = typeof (param);
                if (t == 'string' || t == 'number' || t == 'boolean') {
                    paramStr += '&' + k + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
                }
            }
        }
        
        var reqUrl = url.split('?')[0];
        if (paramStr) {
            reqUrl = reqUrl + "?" + paramStr;
        }
        return reqUrl;
    }

    raxControl.openCertificateUrl = function(batchId){
 
        var tokenUrl = rest.post("/Interaction/MQToFSRestCtrl/getTokenUrl",{}).strVal();
        var fsUrl = rest.post("/Interaction/MQToFSRestCtrl/getFSUrl",{"batchId":batchId}).strVal();
        var defer = $.Deferred();
        $.ajax({
            url:tokenUrl,
            type:"POST",
            success:function(e){
                defer.resolve(e);
            },
            error:function(e){
                defer.rejected();
            }
        });
        defer.done(function(e){
            window.open(fsUrl+ "&um_code="+page.profile.user.userId+"&access_token=" +e.access_token);
        })
    }
    
    
    raxControl.barcodeDownload = function(barcode){
         var result = rest.post("/Interaction/BarcodeDownloadRestCtrl/downloadServer",{"json":barcode},true).jsonVal();
         var times = 0; //循环次数
         var maxTimes = 360;//最大轮询次数
         var intervalTime = 5000;//轮询间隔时间，毫秒
         var downloadStauts = rest.get("/Interaction/BarcodeDownloadRestCtrl/getDownloadStauts",{"serialNo":result.serialNo}).strVal();
         var dtd = $.Deferred();  
		 var sendToItcPrint = setInterval(function() {
		     times++;
		     var flag = false;
			 if(downloadStauts == "Y"){
				  window.open(rax.resfUrl("/Interaction/BarcodeDownloadRestCtrl/downloadLocal?filePath="+result.filePath+"&fileName="+result.fileName),'_self');   
				  clearInterval(sendToItcPrint);
				  flag = true; 
				  dtd.resolve(flag);
			 } else if (downloadStauts == "E") {
				 rest.get("/Interaction/BarcodeDownloadRestCtrl/deleteFilePath",{"filePath":result.filePath,"fileName":result.fileName}).strVal();
				 clearInterval(sendToItcPrint);  
			     flag = false;
			     dtd.reject(flag);
			 }
			 downloadStauts = rest.get("/Interaction/BarcodeDownloadRestCtrl/getDownloadStauts",{"serialNo":result.serialNo}).strVal();			
			 if(times == maxTimes){
				 rest.get("/Interaction/BarcodeDownloadRestCtrl/deleteFilePath",{"filePath":result.filePath,"fileName":result.fileName}).strVal();
			     clearInterval(sendToItcPrint);  
			     flag = false;
			     dtd.reject(flag);
		     }			 
		 },intervalTime);
		 return dtd.promise();
    }

    raxControl.printSuccRefresh = function(serialNo){
        var dtd = $.Deferred();  
            var times = 0; //循环次数
            var maxTimes = 1210;//最大轮询次数
            var intervalTime = 3000;//轮询间隔时间，毫秒
            var printStauts = rest.get("/Interaction/StamperPrint/StamperPrintRestCtrl/getContractPrintStauts",{"serialNo":serialNo}).strVal();
            var sendToItcPrint = setInterval(function() {
                var flag = false;
                
                if(printStauts == "Y"){
                    clearInterval(sendToItcPrint);
                    flag = true; 
                    dtd.resolve(flag);
                } else if (printStauts == "E") {
                   clearInterval(sendToItcPrint);  
                   flag = false;
                   dtd.reject(flag);
                }
                printStauts = rest.get("/Interaction/StamperPrint/StamperPrintRestCtrl/getContractPrintStauts",{"serialNo":serialNo}).strVal();
            
                times++;
                if(times == maxTimes){
                   clearInterval(sendToItcPrint);  
                   flag = false;
                   dtd.reject(flag);
                }
            },intervalTime);
            return dtd.promise();
    }
    

    raxControl.urlHandler = urlHandler;

    raxControl.openInPage = function(url, myParam, position){
        // if (url.indexOf("?") > -1) {
        //     alert("URL参数中不能带？");
        //     return;
        // }
        var reqUrl = urlHandler(url, myParam);
        reqUrl = rax.url(reqUrl);
        window.open(reqUrl,position);
    }

    raxControl.openInTabs = function (url, myParam, tabName, header, encode) {
        var scope = searchControllerScope("#main-content");
        // if (url.indexOf("?") > -1) {
        //     alert("URL参数中不能带？");
        //     return;
        // }
        var sessionKeyName = "X-SESSION-TOKEN";
        var tokenValue = sessionStorage.getItem(sessionKeyName) || localStorage.getItem(sessionKeyName);
        console.log('sessionStorage',sessionStorage.getItem(sessionKeyName),localStorage.getItem(sessionKeyName));
        console.log("X-SESSION-TOKEN",tokenValue);
        sessionStorage.setItem("X-SESSION-TOKEN", tokenValue);
        
        var serialParams = $.extend({}, page.param, myParam);
        var reqUrl = urlHandler(url, serialParams, encode);
        console.log("open-in-main-tab:" + reqUrl);
        if (!scope) {
            console.warn("在当前窗口栈中，没有找到主窗口$scope");
            open(rax.url(reqUrl));
        } else {
            //新加状态参数，0表示非主导航tab页
            scope.openPageInTabs(reqUrl, tabName, header, 1);
        }
    };
    
    raxControl.closeCurrTab = function(){
        var scope = searchControllerScope("#main-content");
        scope.$apply(function(){
            scope.closeCurrTab();
        });
    }

    raxControl.refreshActiveTab = function(){
        var scope = searchControllerScope("#main-content");

        scope.$apply(function(){
            var item = scope.getActiveTab();
            if(item){
                scope.refreshTabContent(item);
            }
        });
    }

    raxControl.selectTabItem = function(tabname){
        var scope = searchControllerScope("#main-content");
        if(!scope) return;
        scope.$apply(function(){
            var item = scope.findTabByName(tabname);
            if(item){
                scope.selectTabItem(item);
            }
        });
    }

    raxControl.refreshTabItem = function(tabname){
        var scope = searchControllerScope("#main-content");
        if(!scope) return;
        scope.$apply(function(){
            var item = scope.findTabByName(tabname);
            if(item){
                scope.refreshTabContent(item);
            }
        });
    }

    raxControl.closeTabItem = function(tabname){
        var scope = searchControllerScope("#main-content");
        if(!scope) return;
        scope.$apply(function(){
            var item = scope.findTabByName(tabname);
            if(item){
                scope.closeTabItem(item);
            }
        });
    }
    raxControl.refreshCurrUrl = function(){
        var win = raxControl.searchRootWindow();
        win.location.reload(true);
        // console.log('win',win);
    }

    raxControl.getCurrIframe = function(){
        var scope = searchControllerScope("#main-content");
        var item = scope.getActiveTab();
        var ifrname = "iframe" + item.id;
        ifrname = ifrname.replace(new RegExp("-", 'gm'), '');
        var iframe = window.frames;
        return iframe;
    }

    raxControl.getRootIframe = function(){
        // var win = window;
        // console.log(win,win.parent)
        var win = window;
        while(true){

            if(win === win.parent){
                break;
            }
            win = win.parent;
        }

        return win;
    }

    raxControl.refreshTabItemIframe = function(tabName, iframeId){
        var scope = searchControllerScope("#main-content");
        if(!scope) return;
        var item = scope.findTabByName(tabName);
        if(!item)return;
        var win = raxControl.getRootIframe();
        if(!win)return;
        console.log($('iframe',win.document.body));
        var iframe = $('#'+scope.genIframeName(item),win.document.body);
        if(!iframe || !iframe.length)return;
        var object = $('#'+iframeId,iframe[0].contentWindow.document.body);
        if(!object || !object.length)return;
        object[0].contentWindow.location.reload();
    }


    raxControl.getIframeById = function(iframeId){
        var win = {contentWindow : raxControl.getRootIframe()};
        if(!win.contentWindow)return;

        var result = null;
        function ti(data,index){
            var node = data;
            var children = [];
            if(node && node.contentWindow && node.contentWindow.document && node.contentWindow.document.body){
                children = $('iframe',node.contentWindow.document.body);
            }
            if(!(children && children.length)){
                return;
            }

            while(index < children.length){
                // console.log(children[index].id)
                if(children[index].id === iframeId){
                    result = children[index];
                    return;
                }   
                ti(children[index],0);
                index++;
            }   
        }
        ti(win,0);
        return result;
    }

    raxControl.refreshParentTab = function(params){
        var win = raxControl.searchRootWindow();
        var id = win.location.href.split('#')[1];
        var scope = searchControllerScope("#main-content");
        var item =  scope.findTabItem(id);
        scope.refreshTabContent(item,params);
    }

    raxControl.closeParentTab = function(){
        var win = raxControl.searchRootWindow();
        var id = win.location.href.split('#')[1];
        var scope = searchControllerScope("#main-content");
        var item =  scope.findTabItem(id);
        scope.closeTabItem(item);
    }

    raxControl.refreshCurrIframe = function(){
        window.location.reload();
    }

    raxControl.onTabStatusRegister = function(status,config){
        var win = raxControl.getCurrIframe();
        if(!win)return;
        while(!win.onStatusRegister){
        	if (win === win.parent && win === win.top) {
                break;
            }
        	win = win.parent;
        }
        if(!win.onStatusRegister){
        	alert("缺少onStatusRegister函数");
        	return;
        }
        win.onStatusRegister(status,config);
    }
    /**
     * 对话框操作相关API
     */



    raxControl.openModalDialog = function (options) {
        // var modalDialog = $('#main-modal-dialog');
        var scope = searchControllerScope("#main-modal-dialog");
        return scope.openModalDialog("DialogContent.jsp");
    };
    raxControl.closeModalDialog = function () {
        var scope = searchControllerScope("#main-modal-dialog");
        console.log("closeModalDialog");
        scope.closeModalDialog();
    };
    raxControl.updateModalDialogData = function (data) {
        console.log("updatedata");
        console.log(data);
        var scope = searchControllerScope("#main-modal-dialog");
        scope.dialogData = data;
    };

    raxControl.searchRootWindow = function () {
        //往上找，找到所有窗口
        var _curWindow = window;
        while (_curWindow) {
            //当前和父窗口相等，说明是同一个窗口了
            // console.log(_curWindow)
            if (_curWindow === _curWindow.parent && _curWindow === _curWindow.top) {
                break;
            }
            _curWindow = _curWindow.parent;
        }
        return _curWindow;
    };

    raxControl.blockUI = function (options) {
        options = $.extend(true, {}, options);
        var html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '') + '"><span><i class="glyphicon glyphicon-hourglass"></i>&nbsp;&nbsp;' + (options.message ? options.message : 'LOADING...') + '</span></div>';
        // if (options.animate) {
        //     html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '') + '">' + '<div class="block-spinner-bar"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>' + '</div>';
        // } else if (options.iconOnly) {
        //     html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '') + '"><img src="' + this.getGlobalImgPath() + 'loading-spinner-grey.gif" align=""></div>';
        // } else if (options.textOnly) {
        //     html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '') + '"><span>&nbsp;&nbsp;' + (options.message ? options.message : 'LOADING...') + '</span></div>';
        // } else {
        //     html = '<div class="loading-message ' + (options.boxed ? 'loading-message-boxed' : '') + '"><img src="' + this.getGlobalImgPath() + 'loading-spinner-grey.gif" align=""><span>&nbsp;&nbsp;' + (options.message ? options.message : 'LOADING...') + '</span></div>';
        // }

        if (options.target) { // element blocking
            var el = $(options.target);
            if (el.height() <= ($(window).height())) {
                options.cenrerY = true;
            }
            el.block({
                message: html,
                baseZ: options.zIndex ? options.zIndex : 1000,
                centerY: options.cenrerY !== undefined ? options.cenrerY : false,
                css: {
                    top: '10%',
                    border: '0',
                    padding: '0',
                    backgroundColor: 'none'
                },
                overlayCSS: {
                    backgroundColor: options.overlayColor ? options.overlayColor : '#555',
                    opacity: options.boxed ? 0.05 : 0.1,
                    cursor: 'wait'
                }
            });
        } else { // page blocking
            $.blockUI({
                message: html,
                baseZ: options.zIndex ? options.zIndex : 1000,
                css: {
                    border: '0',
                    padding: '0',
                    backgroundColor: 'none'
                },
                overlayCSS: {
                    backgroundColor: options.overlayColor ? options.overlayColor : '#555',
                    opacity: options.boxed ? 0.05 : 0.1,
                    cursor: 'wait'
                }
            });
        }
    };

    raxControl.unblockUI = function (target) {
        if (target) {
            $(target).unblock({
                onUnblock: function () {
                    $(target).css('position', '');
                    $(target).css('zoom', '');
                }
            });
        } else {
            $.unblockUI();
        }
    };

    raxControl.block = function (_message, _container, _color) {
        function _block(config){
            var tpl = $('<div class="blockUI" style="position:absolute;cursor:wait;top:0;left:0;z-index:999;width:100%;height:100%;border-radius:5px;background-color:rgba(0,0,0,.5)"></div>');
            this.append(tpl);
            this.css('position','relative');
            config.message = config.message || 'loading...';
            var color = config.color || 'white';
            var inner = $('<div style="display:table;width:100%;height:100%;color:'+color+'"><div class="block-container" style="display:table-cell;text-align:center;padding-top:5%;"><i class="fa fa-spinner spinner"></i><br/><div class="inner"></div></div>');
            $('.inner',inner).html(config.message);
            inner.css(config.css || {});
            tpl.html(inner);
        }
        var container = _container || $("body"),
            message = _message || null;

        _block.call(container, {
            'message': message,
            'color': _color,
            // 'css': {
            //     padding: 5,
            //     margin: 0,
            //     width: '30%',
            //     top: '40%',
            //     left: '35%',
            //     textAlign: 'center',
            //     color: 'white',
            //     border: 'none',
            //     backgroundColor: 'transparent',
            //     cursor: 'wait'
            // }
        });
    };
    raxControl.unblock = function (_container) {
        var container = _container || $("body");
        // container.unblock();
        $('.blockUI', container).remove()
    };

//    raxControl.closeCurrTab = function(){
//        console.log(scope)
//    }

    

    raxControl.pageJumpDelay = function(url, tip, interval, pos){
        pos = pos || '_blank';
        interval = +interval || 3;
        tip = tip || "即将跳转...";
        rax.block('<div id="interval-block" style="font-size:x-large;font-weight:bold">'+tip+'</div>',null,'#0f0');
        var count = interval;
        var interval = setInterval(function(){
            if(!count){
                clearInterval(interval);
                $('#interval-block',$('body')).remove();
                rax.unblock();
                rax.closeCurrTab();
                window.open(url, pos);
            }else{
                $('#interval-block',$('body')).html(tip+ ' ' +count +' 秒');
                count --;
            }
        },1000)
    }

    raxControl.pageJumpDelay2 = function(url, tip, interval, pos){
        pos = pos || '_blank';
        interval = +interval || 3;
        tip = tip || "即将跳转...";
        rax.block('<div id="interval-block" style="font-size:x-large;font-weight:bold">'+tip+'</div>',null,'#0f0');
        var count = interval;
        var interval = setInterval(function(){
            if(!count){
                clearInterval(interval);
                $('#interval-block',$('body')).remove();
                rax.unblock();
                window.open(url, pos);
            }else{
                $('#interval-block',$('body')).html(tip+ ' ' +count +' 秒');
                count --;
            }
        },1000)
    }

    raxControl.logout = function () {
        resta.get('/LoginRestCtrl/logout');
        if (top) {
            top.location.replace(rax.url(""));
        } else {
            location.replace(rax.url(""));
        }
    };
    raxControl.showSessionTimeout = function () {
       rax.popDomModal({
            'title': '连接超时',
            'content': '系统会话超时，请重新登录',
            'width':'600px',
            'buttons': [
                ["忽略", "cancel", "glyphicon glyphicon-eye-close", "btn-default"],
                ["重新登录", "relogin", "glyphicon glyphicon-log-out", "btn-primary"]
            ]
        }).done(function (r) {
            if (r && r.handle == "relogin") {
                rax.logout();
            }
        }).fail(function () {
        });


    };

    raxControl.refreshCustomizeIframeTab = function (tabName) {
        var win = raxControl.getCurrIframe();
        if(!win)return;
        var tabGroup =$('.tabbable-line',$(win.parent.document.body));
        if(!tabGroup.length)return;
        var tabs = $(tabGroup.children()[0]).children();
        // debugger
        for(var i=0; i<tabs.length; i++){
            if(tabs[i].children[0].innerHTML.trim() === tabName.trim()){
                var content = $($(tabGroup.children()[1]).children()[i]);
                var iframe = $('iframe',content);
                iframe.attr('src',iframe.attr('src'));
            }
        }
    }

    raxControl.fileDownload = $.fileDownload;

    raxControl.depends = {};
    // raxControl.depends.owinfo = ['patch','720kb.datepicker','ng-select2','ng-currencyformat','rax.ow','fixedLayout','rax.global.service','ui.select2','ng-numberformat','checklist-model','ui.upload'];
    // raxControl.depends.owlist = ['ngTouch', 'ui.grid','ui.grid.edit', 'ui.grid.cellNav','ui.grid.resizeColumns','ui.grid.moveColumns','ui.grid.selection','ui.grid.autoResize','720kb.datepicker','smartTable.table','rax.ow','fixedLayout','tm.pagination','ui.select2','ui.upload'];
    raxControl.depends.formcell = [];
    raxControl.depends.owinfo = ['patch','720kb.datepicker', 'ng-select2','ng-currencyformat','rax.ow','rax.global.service','ui.select2','ng-numberformat','checklist-model', 'ui.upload', 'ui.bootstrap.datetimepicker','fixedLayout', 'checklist-model', 'rx.formcell','image-viewer'];
    raxControl.depends.owlist = ['ngTouch','720kb.datepicker','smartTable.table','rax.ow','fixedLayout','tm.pagination','ui.select2','ui.upload',"ui.bootstrap.datetimepicker",'checklist-model',"rx.formcell","image-viewer"];
    // raxControl.depends.owlist = ['ngTouch', 'ui.grid','ui.grid.edit', 'ui.grid.cellNav','ui.grid.resizeColumns','ui.grid.moveColumns','ui.grid.selection','ui.grid.autoResize','720kb.datepicker','smartTable.table','rax.ow','fixedLayout','tm.pagination','ui.select2','ui.upload',"ui.bootstrap.datetimepicker",'checklist-model',"rx.formcell"];



    //都给rax对象
    $.extend(rax, raxControl);


})(window);